﻿// News Framework
// (C) Tanzim Saqib. Oct 25, 2010.
// http://TanzimSaqib.com | http://newsfx.codeplex.com

namespace TanzimSaqib.NewsFramework
{
    using System.Collections.Generic;
    using System;
    using System.Linq;

    internal sealed class FeedData
    {
        public static Dictionary<string, Feed> Feeds { get; set; }
        public static Dictionary<string, RssItem> RSSItems { get; set; }

        static FeedData()
        {
            LoadFromStorage();
        }

        public static void LoadFromStorage()
        {
            Feeds = Fx.Instance.ReadFeedItems() ?? new Dictionary<string, Feed>();
            RSSItems = Fx.Instance.ReadRssItems() ?? new Dictionary<string, RssItem>();
        }

        private static Feed GetFeedItem(FeedInfo feed, RssResponse response)
        {
            return new Feed()
            {
                Title = response.Title,
                IsLoaded = true,
                Description = response.Description,
                URL = response.URL,

                FeedDefinition = new FeedDef()
                {
                    Subtitle = feed.Subtitle,
                    Title = feed.Title,
                    URL = feed.URL
                },

                Items = response.Items
            };
        }

        public static void DeleteRssItem(RssItem item)
        {
            if (RSSItems.ContainsKey(item.Link))
                RSSItems.Remove(item.Link);

            var list = (from i in RSSItems select i.Value).ToList();
            StorageHelper.SaveFile(FxConstants.RSSItemsXmlFileName, list);
        }

        public static void SaveRssItem(RssItem item)
        {
            if(!RSSItems.ContainsKey(item.Link))
                RSSItems.Add(item.Link, item);

            var list = (from i in RSSItems select i.Value).ToList();
            StorageHelper.SaveFile(FxConstants.RSSItemsXmlFileName, list);
        }

        public static void Load(FeedInfo feed, Action<FeedResponse> callback)
        {
            Check.Null(Fx.ExtendedParser);

            RssClient.FetchRssAsync(feed.URL, Fx.Instance.RssItemCount, Fx.ExtendedParser, (response) =>
            {
                if (response.Error == default(Exception))
                {
                    var feedItem = GetFeedItem(feed, response);
                    Feeds[feed.URL] = feedItem;

                    Fx.Instance.SaveFeedItems(Feeds);
                    callback(new FeedResponse() { Item = feedItem });
                }
                else
                {
                    callback(new FeedResponse() { Error = response.Error });
                }

            });
        }
    }
}
